import * as Knex from 'knex';
import {
  init, provide, scope, ScopeEnum, inject, config,
} from 'midway';
// import { attachPaginate } from 'knex-paginate';
// @ts-ignore
import * as knexStringcase from 'knex-stringcase';


export interface EntityManager {
  db: Knex
}


// 实体管理器
@scope(ScopeEnum.Singleton)
@provide('em')
export default class EntityManagerImpl implements EntityManager {

  // 可以定义多个数据库
  public db!: Knex;

  @inject()
  appDir: string | undefined; // 当前项目的根目录

  @config('env')
  env: string|undefined;

  @init()
  public connect() {
    console.info(' =====init db========');
    let env: string;
    switch (this.env) {
      case 'local':
        env = 'development';
        break;
      case 'test':
        env = 'test';
        break;
      case 'prod':
        env = 'production';
        break;
      default:
        env = this.env || '';
    }

    // eslint-disable-next-line @typescript-eslint/no-require-imports
    const knexConfig: Knex.Config = require(`${this.appDir}/knexfile.js`)[env];
    const dbConfig = knexStringcase(knexConfig); // 字段改为驼峰格式

    this.db = Knex(dbConfig);
    // attachPaginate(); // 启用注册插件
  }

}
